package progress.exa29_1.ui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client extends Application {
    DataOutputStream toServer=null;//声明输出流
    DataInputStream fromServer=null;//声明输入流

    public void start(Stage primaryStage) {

        BorderPane paneForTextField=new BorderPane();
        paneForTextField.setPadding(new Insets(5,5,5,5));
        paneForTextField.setStyle("-fx-border-color:green");
        paneForTextField.setLeft(new Label("请输入半径："));

        TextField tf = new TextField();
        tf.setAlignment(Pos.BOTTOM_RIGHT);
        paneForTextField.setCenter(tf);

        BorderPane mainPane = new BorderPane();
        TextArea ta = new TextArea();
        mainPane.setCenter(new ScrollPane(ta));
        mainPane.setTop(paneForTextField);

        Scene scene=new Scene(mainPane,450,200);
        primaryStage.setTitle("Client");
        primaryStage.setScene(scene);
        primaryStage.show();

        tf.setOnAction(e->{
            try{
                double radius = Double.parseDouble(tf.getText().trim());
                //将radius写入输出流发送出去
                toServer.writeDouble(radius);
                toServer.flush();//清空输出流
                //从输入流中获取的值赋给area(此方法会阻塞)
                double area = fromServer.readDouble();
                ta.appendText("半径："+radius+'\n');
                ta.appendText("面积是： "+area+'\n');
            }catch (IOException ex) {
                System.err.println(ex);
            }
        });
        try{
            //创建套接字
            Socket socket = new Socket("localhost",8000);

            //创建客户端接受和发送数据的流
            fromServer = new DataInputStream(socket.getInputStream());
            toServer = new DataOutputStream(socket.getOutputStream());

        }catch(IOException ex) {
            ta.appendText(ex.toString()+'\n');
        }
    }
}
